#!/usr/bin/env python

import collections
import glob
import optparse
import os
import sys

import batchcat
from batchcat.jobscripts import SlurmScript
from charmicat import BadCommandLineError


from ypipi import generic_mc_ofname, data_ofname

ofname_generators = {'charm': generic_mc_ofname,
                     'bsbs': generic_mc_ofname,
                     'nonbsbs': generic_mc_ofname,
                     'uds': generic_mc_ofname,
                     'HadronBJ': data_ofname,
                     'ypipi': data_ofname}

def main():
    '''
    ypipi_batch_append.py [opts] path/

    Search `path/' for h5 files, and append them into single files according to their
    file names.
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    batchcat.add_options(op)

    opts, args = op.parse_args()

    if len(args) < 1:
        raise BadCommandLineError('Please supply a directory containing PyTables files', -1)

    path_dict = collections.defaultdict(list)
    for path in glob.iglob(os.path.join(args[0], '*.h5')):
        tokens = path.split('-')
        tag = tokens[1] 
        
        key = ofname_generators[tag](tokens) 

        path_dict[key].append(path)


    scripts = {}
    for key in path_dict:
        cmdline = 'ptappend.py nt {0} '.format(os.path.join(opts.bcat_outdir, key))
        cmdline += ' '.join(path_dict[key])

        scrobj = SlurmScript('ptappend', cmdline, opts)

        batchcat.resource_managers['olympus'].add_script(scrobj)
        
    if opts.bcat_write is not None:
        batchcat.resource_managers['olympus'].write(path=opts.bcat_write)
    else:
        batchcat.resource_managers['olympus'].submit()

    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
